/*   Shotscreens
 *   Copyright (C) 2010, Vadim Zakondyrin (http://crystalnix.com)
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "qgraphicsbrushitem.h"

QGraphicsBrushItem::QGraphicsBrushItem(const QPen & pen, QGraphicsItem *parent) :
    QGraphicsItemGroup(parent)
{
    setPen(pen);


}

QGraphicsBrushItem::~QGraphicsBrushItem()
{

}

void QGraphicsBrushItem::addItemByPointOnScene(const QPointF &point)
{
    QGraphicsLineItem * newPoint = new QGraphicsLineItem(this);

    if (brushPoints.isEmpty()) {
        newPoint->setLine(QLineF(point, point));

        initializeBoundingRect(newPoint->boundingRect());
    } else {
        newPoint->setLine(QLineF(brushPoints.last()->line().p2(), point));
    }

    initializeNewPoint(newPoint);
    brushPoints.push_back(newPoint);
}

void QGraphicsBrushItem::initializeNewPoint(QGraphicsLineItem *point)
{
    point->setPen(getPen());
    updateBoundingRect(point->boundingRect());
}

void QGraphicsBrushItem::clearPoints()
{
    QGraphicsLineItem * point;
    while (!brushPoints.isEmpty()) {
        point = brushPoints.takeLast();
        removeFromGroup(point);
        delete point;
    }
}
int QGraphicsBrushItem::GetTotalPoints()
{
    return brushPoints.count();
}

void QGraphicsBrushItem::DelPointByIndex(int index)
{

    brushPoints.removeAt(index);
}
void QGraphicsBrushItem::SetPointByIndex(int index, QPoint point)
{
    Q_UNUSED(index);
    Q_UNUSED(point);
}

void QGraphicsBrushItem::setPen(const QPen & pen)
{
    m_pen = pen;
    m_pen.setCapStyle(Qt::RoundCap);
    QListIterator<QGraphicsLineItem *> iterator(brushPoints);
    QGraphicsLineItem * point;
    while (iterator.hasNext()) {
        point = iterator.next();
        point->setPen(m_pen);
    }
}

void QGraphicsBrushItem::initializeBoundingRect(const QRectF &rect)
{
    m_boundingRect = rect;
}

void QGraphicsBrushItem::updateBoundingRect(const QRectF &rect)
{
    if (m_boundingRect.bottom() < rect.bottom()) {
        m_boundingRect.setBottom(rect.bottom());
    }

    if (m_boundingRect.top() > rect.top()) {
        m_boundingRect.setTop(rect.top());
    }

    if (m_boundingRect.left() > rect.left()) {
        m_boundingRect.setLeft(rect.left());
    }

    if (m_boundingRect.right() < rect.right()) {
        m_boundingRect.setRight(rect.right());
    }
}
